<?php
/**
echo "Start Scan Uploaded Video\n";
$file=getFile("upload");
for ($num=0;!empty($file[$num]);$num++){
    echo "[File]Find ".$file[$num]."\n";
    echo "[File]Move File to Encoding Dir\n";
    rename('upload\\'.$file[$num],'encoding\\'.$file[$num]);
    echo "[Encode]Start Encode ".$file[$num]."\n";
    echo "[Encode]Set Encode Config\n";
    echo "[Encode]Video_Bitrate:".$encode_bitrate_video."\n";
    echo "[Encode]Audio_Bitrate:".$encode_bitrate_audio."\n";
    echo "[Encode]Time_Per_TS:".$encode_ts_time."\n";
    echo "[Encode]Frame_Per_TS:".$encode_ts_frame."\n";
    echo "[Encode]Encoder:FFMPEG\n";
    $today=date("Ymd",time());
    if (!file_exists("video\\".$today)){
        mkdir ("video\\".$today,0777,true);
        echo "[File]Create Dir '".$today."'\n";
    }
    $hls_dir=Random_String(8);
    echo "[File]Create Dir '".$hls_dir."'\n";
    mkdir ("video\\".$today.DIRECTORY_SEPARATOR.$hls_dir,0777,true);
    $common="ffmpeg.exe -i encoding\\".$file[$num]." -b:v ".$encode_bitrate_video."K -b:a ".$encode_bitrate_audio."K -c:v libx264 -c:a aac -keyint_min ".$encode_ts_frame." -g ".$encode_ts_frame." -sc_threshold 0 -strict -2 -f hls -hls_list_size 0 -hls_init_time ".$encode_ts_time." -hls_time ".$encode_ts_time." -hls_segment_filename video\\".$today.DIRECTORY_SEPARATOR.$hls_dir.DIRECTORY_SEPARATOR.$hls_dir."%03d.ts video\\".$today.DIRECTORY_SEPARATOR.$hls_dir."\\index.m3u8";
    echo "[Encode]Starting FFMPEG..........\n";
    sleep(3);
    exec_log($common);
    echo "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
    echo "\e[0;32m[Encode]Encode Done!\n";
    echo "\e[0;32m[File]Delete File ".$file[$num]."\n";
    unlink("encoding\\".$file[$num]);
}**/
echo "[Worker] Initialization\n";
exec('mode con cols=60 lines=36');
echo "[Worker] Loading Function Database\n";
include("include/function.php");
include ("config/config.php");
echo "[Worker] Connecting to Redis\n";
$redis=Redis_Link();
echo "[Worker] Connecting to Mysql\n";
$db_link=DB_Link();
$encode_bitrate_video=Get_Config('encode_bitrate_video');
$encode_bitrate_audio=Get_Config('encode_bitrate_audio');
$encode_ts_time=Get_Config('encode_ts_time');
$encode_ts_frame=Get_Config('encode_ts_frame');
$worker_thread=Get_Config('worker_thread');
echo "[Worker] Register Worker Thread\n";
$init=0;
for ($i=1;$i<=$worker_thread&&$init==0;$i++){
    $status=$redis->get('Worker_Status_'.$i);
    if (empty($status)){
        $redis->set('Worker_Status_'.$i,'1');
        $redis->expire('Worker_Status_'.$i,10);
        echo "[Worker] Register Success\n";
        exec_log('title Worker '.$i.'# [Free]');
        $worker_no=$i;
        $init=1;
    }
}
if ($init==0){
    echo "[Worker] Full! Exit in 5 sec\n";
    sleep(5);
    exit;
}
echo "[Worker] Create VM\n";
if (file_exists("VM".DIRECTORY_SEPARATOR."ffmpeg_vm_".$worker_no.".exe")){
    unlink("VM".DIRECTORY_SEPARATOR."ffmpeg_vm_".$worker_no.".exe");
}
exec_log("copy /y ffmpeg.exe VM".DIRECTORY_SEPARATOR."ffmpeg_vm_".$worker_no.'.exe');
start:
//Dynamic Load Config
$encode_bitrate_video=Get_Config('encode_bitrate_video');
$encode_bitrate_audio=Get_Config('encode_bitrate_audio');
$encode_ts_time=Get_Config('encode_ts_time');
$encode_ts_frame=Get_Config('encode_ts_frame');
$worker_thread=Get_Config('worker_thread');
$subtitle_file=Get_Config('subtitle_file');
$video_dir=Get_Config('video_dir');
//
$work=$redis->get('Work_Info_'.$worker_no);
if (!empty($work)) {
    $redis->set('Worker_Status_' . $worker_no, '2');
    $work = json_decode($work, true);
    exec('title Worker ' . $worker_no . '# [Busy]');
    echo "[Worker] Get Work.\n";
    echo "[Worker] Find Work Data\n";
    $row_work = mysqli_fetch_array(mysqli_query($db_link, "SELECT * FROM video_list WHERE ID = '" . $work['ID'] . "'"));
    echo "[Worker] Update Work Status\n";
    mysqli_query($db_link, "UPDATE `video_list` SET `status` = '1' WHERE `ID` = " . $work['ID'] . ";");
    echo "[Encode] Filename:" . $row_work['filename'] . "\n";

    //add by bendy [got media file info]
    $videoinfo = getVideoInfo("encoding" . DIRECTORY_SEPARATOR . $row_work['filename']);
    $add_sub=false;
    //检查有没有同名字幕文件
    $fn=pathinfo($row_work['filename'],PATHINFO_FILENAME);
    $chkext[]="ass";
    $chkext[]="srt";
    foreach ($chkext as $ext){
        $cn='upload/'.$fn.".".$ext;
        if (is_file($cn)){
            $add_sub=true;
            $sub_file=$fn.".".$ext;
        }
    }
    if (is_array($videoinfo)){
        $m_time = $videoinfo[0][seconds];
        $m_size = $videoinfo[0][size];
        echo "[Encode] Video time:" . $m_time . "\n";
        mysqli_query($db_link, "UPDATE `video_list` SET `m_time` = $m_time , `m_size` = $m_size WHERE `ID` = " . $work['ID'] . ";");
        //end


        $today=$row_work['day'];
        if (!file_exists($video_dir.DIRECTORY_SEPARATOR.$today)){
            mkdir ($video_dir.DIRECTORY_SEPARATOR.$today,0777,true);
            echo "[File]Create Dir '".$today."'\n";
        }
        $hls_dir=$row_work['random'];
        echo "[File] Create Dir '".$hls_dir."'\n";
        mkdir ($video_dir.DIRECTORY_SEPARATOR.$today.DIRECTORY_SEPARATOR.$hls_dir,0777,true);

        //add 截图
        $sc_jpeg_start_time=Get_Config('sc_jpeg_start_time');
        $sc_jpeg_res=Get_Config('sc_jpeg_res');
        $common="VM".DIRECTORY_SEPARATOR."ffmpeg_vm_".$worker_no.".exe -i encoding".DIRECTORY_SEPARATOR.$row_work['filename']." -y -f image2 -ss $sc_jpeg_start_time -t 0.001 -s $sc_jpeg_res  ".$video_dir.DIRECTORY_SEPARATOR.$today.DIRECTORY_SEPARATOR.$hls_dir.DIRECTORY_SEPARATOR."1.jpg";
        echo "[Encode] start got photo\n";
        exec_log($common);

        //加字幕
        //检查有没有同名字幕文件
        $sub_add='';
        if ($add_sub){
            $sub_add="subtitles='upload/".$sub_file."'";
        }
        w_log("1:".$sub_add);


        if (file_exists($subtitle_file)){
            if ($sub_add<>"") {
                $sub_add = "-vf subtitles='" . $subtitle_file . "'," . $sub_add;
            }
            else{
                $sub_add = "-vf subtitles=" . $subtitle_file ;
            }
        }
        w_log("2:".$sub_add);
        //
        $video_res=Get_Config('video_res');
        if ($video_res <> 0){
            $sub_add=$sub_add." -s ".$video_res;
        }
        w_log("3:".$sub_add);
        $common="VM".DIRECTORY_SEPARATOR."ffmpeg_vm_".$worker_no.".exe -i encoding".DIRECTORY_SEPARATOR.$row_work['filename']." ".$sub_add." -b:v ".$encode_bitrate_video."K -b:a ".$encode_bitrate_audio."K -c:v libx264 -c:a aac -keyint_min ".$encode_ts_frame." -g ".$encode_ts_frame." -sc_threshold 0 -strict -2 -f hls -hls_list_size 0 -hls_init_time ".$encode_ts_time." -hls_time ".$encode_ts_time." -hls_key_info_file ".$video_dir.DIRECTORY_SEPARATOR.$today.DIRECTORY_SEPARATOR.$hls_dir.DIRECTORY_SEPARATOR. "key_info -hls_segment_filename ".$video_dir.DIRECTORY_SEPARATOR.$today.DIRECTORY_SEPARATOR.$hls_dir.DIRECTORY_SEPARATOR.$hls_dir."%03d.ts ".$video_dir.DIRECTORY_SEPARATOR.$today.DIRECTORY_SEPARATOR.$hls_dir.DIRECTORY_SEPARATOR."index.m3u8";
        echo "[Encode] Setting Encryption Key\n";
        $en_file=fopen($video_dir.DIRECTORY_SEPARATOR.$today.DIRECTORY_SEPARATOR.$hls_dir.DIRECTORY_SEPARATOR."key.key",'w');
        fwrite($en_file,Random_String(16));
        fclose($en_file);
        $en_file=fopen($video_dir.DIRECTORY_SEPARATOR.$today.DIRECTORY_SEPARATOR.$hls_dir.DIRECTORY_SEPARATOR."key_info",'w');
        fwrite($en_file,"key.key\r\n".$video_dir.DIRECTORY_SEPARATOR.$today.DIRECTORY_SEPARATOR.$hls_dir.DIRECTORY_SEPARATOR."key.key");
        fclose($en_file);
        echo "[Encode] Starting FFMPEG..........\n";
        sleep(3);
        exec_log($common);
        mysqli_query($db_link,"UPDATE `video_list` SET `status` = '2' WHERE `ID` = ".$work['ID'].";");
    }else{
        echo  "[Encode] Bad file:" . $m_time . "\n";
        copy('encoding/'.$row_work['filename'],'badfile/'.$row_work['filename']);
        mysqli_query($db_link, "UPDATE `video_list` SET `status` = '3'  WHERE `ID` = " . $work['ID'] . ";");

    }
    echo "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
    echo "[Encode] Encode Done!\n";
    echo "[File] Delete File ".$row_work['filename']."\n";

    unlink("encoding/".$row_work['filename']);
    if ($add_sub and $sub_file <> ""){
        echo "[File] Delete subtitle File ".$sub_file."\n";
        unlink("upload/".$sub_file);
    }

    echo "[Worker] Done!\n";
    $redis->del('Work_Info_'.$worker_no);
    $redis->set('Worker_Status_'.$worker_no,'1');

}else {
    $redis->set('Worker_Status_' . $worker_no, '1');
    $redis->expire('Worker_Status_' . $worker_no, 10);
    exec('title Worker '.$worker_no.'# [Free]');
}
sleep(5);
//add restart function
$restart=$redis->get('Work_Restart_'.$worker_no);
if ($restart=='yes'){
    $redis->set('Work_Restart_'.$worker_no,"no");
    exit;
}
goto start;